package apt.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import apt.bean.UserBean;
import apt.common.HibernateUtil;

public class UserDao {
	private Session session;
	private Transaction transaction;
	private UserBean userBean;
	private ArrayList<UserBean> arrUserBeans;
	private List<UserBean> listUserBeans;

	public UserDao() {
		userBean = new UserBean();
		arrUserBeans = new ArrayList<>();
	}

	public List<UserBean> getListUser() throws Exception {
		try {
			session = HibernateUtil.getSessionFactory().openSession();

			Query query = session.createQuery("From UserBean");
			listUserBeans = query.list();
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception();
		} finally {
			session.close();
		}
		return listUserBeans;
	}

	public UserBean getUserByID(int id) throws Exception {
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			userBean = (UserBean) session.get(UserBean.class, id);
		} catch (Exception e) {
			throw new Exception();
		} finally {
			session.close();
		}
		return userBean;
	}

	public boolean addUser(UserBean user) {
		session = HibernateUtil.getSessionFactory().openSession();
		try {
			transaction =  session.beginTransaction();
			session.save(user);
			transaction.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return true;
	}

	public boolean updateUser(UserBean user) {
		session = HibernateUtil.getSessionFactory().openSession();
		try {
			transaction = session.beginTransaction();
			session.update(user);
		} catch (Exception e) {
			transaction.rollback();
		} finally {
			transaction.commit();
			session.close();
		}
		return true;
	}
	
	public boolean deleteUser(UserBean user) {
		session = HibernateUtil.getSessionFactory().openSession();
		try {
			transaction = session.beginTransaction();
			session.delete(user);
			transaction.commit();
		} catch (Exception e) {
			transaction.rollback();
		} finally {
			session.close();
		}
		return true;
	}

	public int getUserLogin(String userName, String password) {
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			System.out.println("_-------------------- 1.");
			String sql = "from UserBean where status = true and userName = :user and password = :pass";
			Query query = session.createQuery(sql);
			query.setString("user", userName);
			query.setString("pass", password);

			listUserBeans = query.list();
			System.out.println("---------- count : " + listUserBeans.size());
		} catch (HibernateException e1) {
			e1.printStackTrace();
			return -1;
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		} finally {
			session.close();
		}
		return listUserBeans.size();
	}

}
